//
//  CartViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/15.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit

class CartViewController: BaseViewController {
    var cartTable:UITableView!
    var bottomView:UIView!
    var billBUttuon:UIButton!
    var moneyLabel:UILabel!
    var selectAllBtn:UIButton!
    var noteInfo:UIButton!
    var selectAll:Bool = false
    var editIndexPathSet:NSMutableSet!
    var selectIndexPathSet:NSMutableSet!
    var testDataArray:[String]?
    var tableDataSource:[cartListItem] = []
    var displayDataSource:[[cartListItem]] = []
    var totalMoney:String?
    var note1:NSMutableAttributedString!
    var note2:NSMutableAttributedString!
    @IBAction func billBtnClick(button:UIButton){
        func hasDifferentManufacturer()->Bool{
            var exist = false
            if let firstPath = self.selectIndexPathSet.anyObject() as? NSIndexPath{
                let seciton = firstPath.section
                for indexPath in self.selectIndexPathSet{
                    if indexPath.section != seciton{
                        exist = true
                    }
                }
            }
            return exist
        }
        if selectIndexPathSet.count == 0{
            self.showTips("您还未确认选择任何商品")
            return
        }
        if  hasDifferentManufacturer(){
            self.showTips("订单中不能包含不同仓库的商品")
            return
        }
        self.commitCard(GlobalDataHelper.instance.session)
    }
    @IBAction func selectAllBtnClick(button:UIButton){
        selectAll = !selectAll
        if selectAll{
            selectAllBtn.setBackgroundImage(UIImage(named: "down_checkbox"), forState: UIControlState.Normal)
            self.setAllIndexPathToSelected()
        }
        else{
            selectAllBtn.setBackgroundImage(UIImage(named: "nor_checkbox"), forState: UIControlState.Normal)
            self.removeAllSelectedIndexPath()
        }
        cartTable.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "购物车"
        let barButton = self.editButtonItem()
        barButton.tintColor = UIColor.whiteColor()
        barButton.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(14)], forState: UIControlState.Normal)
        barButton.title = "编辑"
        self.navigationItem.rightBarButtonItem = barButton
        self.setupBottomView()
        self.setupTableView()
        editIndexPathSet = NSMutableSet(capacity: 0)
         selectIndexPathSet = NSMutableSet(capacity: 0)
        noteInfo = UIButton(frame: CGRectMake(0, (view.bounds.size.height-100)/2.0, view.bounds.size.width, 80))
        noteInfo.addTarget(self, action: "noteClick", forControlEvents: UIControlEvents.TouchUpInside)
        let str1:NSString = "您的购物车没有任何商品"
        let str2:NSString = "您的购物车没有任何商品,是否立即登陆"
        note1 = NSMutableAttributedString(string:str1 as String)
        note1.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, str1.length))
        note1.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSMakeRange(0, str1.length))
        note2 =  NSMutableAttributedString(string:str2 as String)
        note2.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, str2.length))
        note2.addAttribute(NSForegroundColorAttributeName, value: commonRedColor, range: NSMakeRange(str2.length-4, 4))
        note2.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSMakeRange(0, str2.length))
         note2.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(17), range:NSMakeRange(str2.length-4, 4))
        note2.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSMakeRange(str2.length-4, 4))
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if let sessionid = GlobalDataHelper.instance.session{
            self.queryCartList(sessionid)
        }
        else{
            self.cleanData()
            noteInfo.setAttributedTitle(note2, forState: UIControlState.Normal)
            view.addSubview(noteInfo)
        }
    }
    func cleanData(){
        self.editIndexPathSet.removeAllObjects()
        self.selectIndexPathSet.removeAllObjects()
        self.displayDataSource.removeAll(keepCapacity: false)
        self.cartTable.reloadData()
        moneyLabel.text = "¥0.00"
    }
    func noteClick(){
        if GlobalDataHelper.instance.session == nil{
            self.goLogin()
            noteInfo.removeFromSuperview()
        }
    }
    func  goLogin(){
        let ctl = LoginViewController()
        ctl.loginSuccess = { userInfo in
            GlobalDataHelper.instance.userId = userInfo?["id"] as? String
            GlobalDataHelper.instance.userInfo = userInfo
            GlobalDataHelper.instance.is_authentication = userInfo?["is_authentication"] as? String
        }
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func queryCartList(sessionid:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        request.requestStart("/cart/list", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                self.tableDataSource = (dic?.pareseDataToCartListArray())!
//                self.totalMoney = dic?["data"]?["base_total"] as? String
                dispatch_async(dispatch_get_main_queue()){
                    self.getDisplayData()
                    self.cartTable.reloadData()
                    if self.displayDataSource.count == 0{
                        self.noteInfo.setAttributedTitle(self.note1, forState: UIControlState.Normal)
                         self.view.addSubview(self.noteInfo)
                    }
                    else{
                        
                         self.noteInfo.removeFromSuperview()
                    }
                    self.moneyLabel.text = self.totalMoney
                }
            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    func genTotal()->Float{
        var total:Float = 0.00
        for indexPath in self.selectIndexPathSet{
            let array = self.displayDataSource[indexPath.section]
            let obj = array[indexPath.row]
            print(obj)
            if  let pc = obj.price{
                let priceStr = pc as NSString
                let price = priceStr.floatValue
                if  let numbers = obj.qty{
                    let numberstr = numbers as NSString
                    let number = numberstr.floatValue
                    total += price*number
                }
            }
        }
        return total
    }
    func genCardString()->NSString{
        if self.selectIndexPathSet.count==0{
            return ""
        }
        let start:NSMutableString = "["
//        for i in 0..<self.selectIndexPathSet.count{
//            let indexPath:NSIndexPath? = self.selectIndexPathSet[i] as? NSIndexPath
//            let array = self.displayDataSource[i]
//            var sr:NSString!
//            sr = NSString(format: "{\"count\":\"%d\",\"productId\":\"%@\"},",goodsInCart[i].number,goodsInCart[i].wine.id!)
//            start.appendString(sr as String)
//        }
        for indexPath in self.selectIndexPathSet{
            var sr:NSString!
            let array = self.displayDataSource[indexPath.section]
            let obj = array[indexPath.row]
            sr = NSString(format: "{\"items_id\":\"%@\"},",obj.id!)
            start.appendString(sr as String)
        }
        start.deleteCharactersInRange(NSMakeRange(start.length-1, 1))
        start.appendString("]")
        return start
    }
    func genCardObj()->NSArray{
        if self.selectIndexPathSet.count==0{
            return []
        }
        let  start:NSMutableArray = []
        for indexPath in self.selectIndexPathSet{
            let array = self.displayDataSource[indexPath.section]
            let obj = array[indexPath.row]
            start.addObject(NSDictionary(object: obj.id!, forKey: "items_id"))
        }
        return start
    }
    func commitCard(sessionid:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        let idInfo = self.genCardString() as String
        parameters.setObject(idInfo,forKey: "selectitems")

        request.requestStart("/cart/selectItem", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        let ctl = ConfirmViewController()
//                        var array:[cartListItem] = []
//                        for indexPath in self.selectIndexPathSet{
//                            if indexPath.row >= self.tableDataSource.count{
//                                return
//                            }
//                            let item = self.tableDataSource[indexPath.row]
//                            array.append(item)
//                        }
//                        ctl.cartDataSource = array;
                        self.navigationController?.pushViewController(ctl, animated: true)
                        self.selectIndexPathSet.removeAllObjects()
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                    })
                    
                }
            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    func setupTableView(){
        cartTable = UITableView(frame:CGRectMake(0, 64, view.bounds.size.width, view.bounds.size.height - tabbarHeight-bottomView.bounds.size.height-64), style: UITableViewStyle.Plain)
        cartTable.delegate = self
        cartTable.dataSource = self
        cartTable.separatorStyle = UITableViewCellSeparatorStyle.None
        let nib = UINib(nibName: "CartCell", bundle: nil)
        cartTable.registerNib(nib, forCellReuseIdentifier: "cartCellID")
        view.addSubview(cartTable)
    }
    func setupBottomView(){
        bottomView = UIView(frame: CGRectMake(0, view.bounds.size.height-tabbarHeight-49, view.bounds.size.width, 49))
        view.addSubview(bottomView)
        //背景
        let line = UIImageView(frame: CGRectMake(0, 0, bottomView.bounds.size.width, onePix))
        line.backgroundColor = commonRedColor
        bottomView.addSubview(line)
        //全选按钮
//        selectAllBtn = UIButton(frame: CGRectMake(15,(bottomView.bounds.size.height-24)/2.0, 24, 24))
//        selectAllBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//        selectAllBtn.setBackgroundImage(UIImage(named:"nor_checkbox"), forState: UIControlState.Normal)
//        selectAllBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
//        selectAllBtn.addTarget(self, action: "selectAllBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
//        bottomView.addSubview(selectAllBtn)
//        let nameLabel = UILabel(frame: CGRectMake(CGRectGetMaxX(selectAllBtn.frame), 0, 40, bottomView.bounds.size.height))
//        nameLabel.textColor = UIColor.darkGrayColor()
//        nameLabel.font = UIFont.boldSystemFontOfSize(13)
//        nameLabel.text = "全 选"
//        nameLabel.textAlignment = NSTextAlignment.Center
//        bottomView.addSubview(nameLabel)
        //总金额
        let allLabel = UILabel(frame: CGRectMake(15, 0, 40, bottomView.bounds.size.height))
        allLabel.textColor = UIColor.darkGrayColor()
        allLabel.font = UIFont.boldSystemFontOfSize(14)
        allLabel.text = "总 额"
        allLabel.textAlignment = NSTextAlignment.Center
        bottomView.addSubview(allLabel)
        moneyLabel = UILabel(frame: CGRectMake(CGRectGetMaxX(allLabel.frame)+5, 0, bottomView.bounds.size.width/2.0-CGRectGetMaxX(allLabel.frame)-5, bottomView.bounds.size.height))
        moneyLabel.textColor = commonRedColor
        moneyLabel.font = UIFont.boldSystemFontOfSize(14)
        moneyLabel.text = "¥0.00"
        bottomView.addSubview(moneyLabel)
        //结账按钮
        billBUttuon = UIButton(frame: CGRectMake(CGRectGetMaxX(moneyLabel.frame),0, bottomView.bounds.size.width - CGRectGetMaxX(moneyLabel.frame), bottomView.bounds.size.height))
        billBUttuon.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        billBUttuon.setTitle("去结算", forState: UIControlState.Normal)
        billBUttuon.titleLabel?.font = UIFont.systemFontOfSize(14)
        billBUttuon.backgroundColor = commonRedColor
        billBUttuon.addTarget(self, action: "billBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        bottomView.addSubview(billBUttuon)
        
    }
    func getDisplayData()->Void{
        self.displayDataSource.removeAll(keepCapacity: false)
        var manufacturerArray:[String] = []
        func existManufacturerArray(manufacturer:String)->(Bool,NSInteger){
            var exist:(Bool,NSInteger) = (false,-1)
            for i in 0..<manufacturerArray.count{
                let str = manufacturerArray[i]
                if str == manufacturer{
                    exist.0 = true
                    exist.1 = i
                    break
                }
            }
            return exist
        }
        for obj in self.tableDataSource{
            //存在
            let result = existManufacturerArray(obj.manufacturer!)
            if !result.0{
                manufacturerArray.append(obj.manufacturer!)
                var array:[cartListItem] = []
                array.append(obj)
                self.displayDataSource.append(array)
            }
            else{
                self.displayDataSource[result.1].append(obj)
            }
        }
    }
    func editClick(barButtonItem:UIButton){
//        self.navigationController?.popViewControllerAnimated(true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
        print(self.editing)
//        cartTable.setEditing(editing, animated: animated)
        if editing{
            self.navigationItem.rightBarButtonItem?.title = "完成"
            self.setAllIndexPathToEdit()
            for cell in cartTable.visibleCells{
                if let acell = cell as? CartCell{
                    acell.enterEditModelAnimationed(true)
                }
            }
        }
        else{
            self.navigationItem.rightBarButtonItem?.title = "编辑"
            self.removeAllEidtIndexPath()
            for cell in cartTable.visibleCells{
                if let acell = cell as? CartCell{
                    acell.exitEditModelAnimationed(true)
                }
            }
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    //编辑的indexPath处理方法
    func setAllIndexPathToEdit()->Void{
        for i in 0..<self.displayDataSource.count{
            for j in 0..<self.displayDataSource[i].count{
                let indexPath = NSIndexPath(forRow: i, inSection: j)
                self.addIndexPathToEdit(indexPath)
            }
        }
    }
    func removeAllEidtIndexPath()->Void{
        self.editIndexPathSet.removeAllObjects()
    }
    func addIndexPathToEdit(path:NSIndexPath)->Void{
        if !self.alreadyExistInSet(path).exist{
            self.editIndexPathSet.addObject(path)
        }
    }
    func removeIndexPathFromEditSet(path:NSIndexPath)->Void{
        let result = self.alreadyExistInSet(path)
        if result.exist{
            self.editIndexPathSet.removeObject(result.existPath!)
            //删除后后面的indexpath都减1
            for indexPath in self.editIndexPathSet{
                if let aPath = indexPath as? NSIndexPath{
                    if result.existPath?.section == aPath.section{
                        if aPath.row > result.existPath?.row{
                            self.editIndexPathSet.removeObject(aPath)
                            let changedPath = NSIndexPath(forRow: aPath.row-1, inSection: aPath.section)
                            self.editIndexPathSet.addObject(changedPath)
                        }
                    }
                }
            }
            let result2 = self.alreadyExistInSelectedSet(path)
            if result2.exist{
                self.selectIndexPathSet.removeObject(result2.existPath!)
            }
            //该删除同时影响选中的indexPath,row大于result中的全部都减1
            for indexPath in self.selectIndexPathSet{
                if let aPath = indexPath as? NSIndexPath{
                    if aPath.section == path.section{
                        if aPath.row > path.row{
                            self.selectIndexPathSet.removeObject(aPath)
                            let changedPath = NSIndexPath(forRow: aPath.row-1, inSection: aPath.section)
                            self.selectIndexPathSet.addObject(changedPath)
                        }
                    }

                }
            }
        }

    }
    func removeDisplayAtSection(deletedSection:NSInteger){
        for indexPath in self.editIndexPathSet{
            if let aPath = indexPath as? NSIndexPath{
                    if aPath.section > deletedSection{
                        self.editIndexPathSet.removeObject(aPath)
                        let changedPath = NSIndexPath(forRow: aPath.row, inSection: aPath.section-1)
                        self.editIndexPathSet.addObject(changedPath)
                }
            }
        }
        for indexPath in self.selectIndexPathSet{
            if let aPath = indexPath as? NSIndexPath{
                if aPath.section > deletedSection{
                    self.selectIndexPathSet.removeObject(aPath)
                    let changedPath = NSIndexPath(forRow: aPath.row, inSection: aPath.section-1)
                    self.selectIndexPathSet.addObject(changedPath)
                }
            }
        }
    }
    func alreadyExistInSet(path:NSIndexPath)->(exist:Bool,existPath:NSIndexPath?){
        var exist = false
        var existPath:NSIndexPath?
        for indexPath in self.editIndexPathSet{
            if let aPath = indexPath as? NSIndexPath{
                if aPath.row == path.row && aPath.section == path.section{
                    exist = true
                    existPath = aPath
                    break
                }
            }
        }
        return (exist,existPath)
    }
    //选中的indexPath的处理方法
    func setAllIndexPathToSelected()->Void{
//        for i in 0..<self.tableDataSource.count{
//            let indexPath = NSIndexPath(forRow: i, inSection: 0)
//            self.addIndexPathToSelected(indexPath)
//        }
    }
    func removeAllSelectedIndexPath()->Void{
        self.selectIndexPathSet.removeAllObjects()
    }
    func addIndexPathToSelected(path:NSIndexPath)->Void{
        if !self.alreadyExistInSelectedSet(path).exist{
            self.selectIndexPathSet.addObject(path)
        }
    }
    func removeIndexPathFromSelectedSet(path:NSIndexPath)->Void{
        let result = self.alreadyExistInSelectedSet(path)
        if result.exist{
            self.selectIndexPathSet.removeObject(result.existPath!)
        }
        
    }
    func alreadyExistInSelectedSet(path:NSIndexPath)->(exist:Bool,existPath:NSIndexPath?){
        var exist = false
        var existPath:NSIndexPath?
        for indexPath in self.selectIndexPathSet{
            if let aPath = indexPath as? NSIndexPath{
                if aPath.row == path.row && aPath.section == path.section{
                    exist = true
                    existPath = aPath
                    break
                }
            }
        }
        return (exist,existPath)
    }

}
extension CartViewController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.displayDataSource.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
//        return GlobalDataHelper.instance.goodsInCart.count
        let array = self.displayDataSource[section]
        return array.count
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 30
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let lbl = UILabel(frame: CGRectMake(0, 0, tableView.bounds.size.width, 30))
        lbl.backgroundColor = commonBackgoundColor
        lbl.font = UIFont.systemFontOfSize(14)
        let array = self.displayDataSource[section]
        if array[0].manufacturer == ""{
            lbl.text = "  仓库号：0"
        }
        else{
            lbl.text = "  仓库号："+array[0].manufacturer!
        }
        return lbl
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("cartCellID", forIndexPath: indexPath) as! CartCell
        let array = self.displayDataSource[indexPath.section]
        var obj = array[indexPath.row]
        cell.indexPath = indexPath
        if self.alreadyExistInSet(indexPath).exist{
            cell.enterEditModelAnimationed(false)
        }
        else{
            cell.exitEditModelAnimationed(false)
        }
        if self.alreadyExistInSelectedSet(indexPath).exist{
            cell.cartItemSelected=true
        }
        else{
            cell.cartItemSelected=false
        }
        cell.cartImageView.setImageWithUrl(obj.image!, defaultImage: nil)
        cell.nameLabel.text = obj.name
        cell.priceLabel.text = obj.price
        if let num = obj.qty{
            let numStr = num as NSString
            cell.numberCountView.currentNumber = numStr.integerValue

        }
        cell.cartItemSelectValueChangedEnclose = {[weak self] apath,selected in
            if selected{
                self?.addIndexPathToSelected(apath)
            }
            else{
                self?.removeIndexPathFromSelectedSet(apath)
            }
            let total = self?.genTotal()
            self!.moneyLabel.text = String(format: "%.02f",total!)
        }
        
        cell.cellDidEnterEditModel = {[weak self,weak cell] indexPath,isEdit in
            print("indexPath:\(indexPath.section),\(indexPath.row)");
            if isEdit{
                self?.addIndexPathToEdit(indexPath)
            }
            else{
                self?.removeIndexPathFromEditSet(indexPath)
            }
            
        }
        //修改购物车中商品数量操作
        cell.numberCountView.numberChangedHandle = {[weak self,weak cell] currentNumber in
            print("currentNumber:\(currentNumber)");
//            self?.updateCartItems(GlobalDataHelper.instance.session, cartitemsid: obj.id, action: "update_qty", qty: "\(currentNumber)")
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
            parameters.setObject(obj.id!, forKey: "cartitemsid")
            parameters.setObject("update_qty", forKey: "action")
            parameters.setObject(currentNumber, forKey: "qty")
            request.requestStart("/cart/update", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self?.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                    }
                    if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self?.displayDataSource[indexPath.section][indexPath.row].qty =  "\(currentNumber)"
                        cell?.numberCountView.currentNumber = currentNumber
                        let total = self?.genTotal()
                        self!.moneyLabel.text = String(format: "%.02f",total!)
                        }
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue()){
                        self?.showTips("操作失败")
                        if let num = obj.qty{
                            let numStr = num as NSString
                            cell?.numberCountView.currentNumber = numStr.integerValue
                            
                        }
                    }
                }
            })
            dispatch_async(dispatch_get_main_queue()){
                self?.showProcess("正在处理...")
            }

        }
        
        //删除购物车中商品操作
        cell.deleteButtonClickHandle = {[weak self,weak cell] currentIndexPath in
            print("indexPath:\(indexPath.section),\(indexPath.row)");
            //            self?.updateCartItems(GlobalDataHelper.instance.session, cartitemsid: obj.id, action: "update_qty", qty: "\(currentNumber)")
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
            parameters.setObject(obj.id!, forKey: "cartitemsid")
            request.requestStart("/cart/delete", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self?.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
//                            self?.tableDataSource.removeAtIndex(currentIndexPath.row)
                            self?.displayDataSource[currentIndexPath.section].removeAtIndex(currentIndexPath.row)
                            self?.removeIndexPathFromEditSet(currentIndexPath)
                            if self?.displayDataSource[currentIndexPath.section].count == 0{
                                self?.displayDataSource.removeAtIndex(currentIndexPath.section)
                                self?.removeDisplayAtSection(currentIndexPath.section)
                            }
                            self?.cartTable.reloadData()
                            if self?.displayDataSource.count == 0{
                                 self?.noteInfo.setAttributedTitle(self?.note1, forState: UIControlState.Normal)
                                self?.view.addSubview((self?.noteInfo)!)
                            }
                            else{
                                self?.noteInfo.removeFromSuperview()
                            }
                            let total = self?.genTotal()
                            self!.moneyLabel.text = String(format: "%.02f",total!)
                        }
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue()){
                        self?.showTips("操作失败")
                    }
                }
            })
            dispatch_async(dispatch_get_main_queue()){
                self?.showProcess("正在处理...")
            }
            
        }
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 80.0
    }
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle{
        return UITableViewCellEditingStyle.None
    }
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
//        var obj = GlobalDataHelper.instance.goodsInCart[indexPath.row]
//        obj.number = 0
//        GlobalDataHelper.instance.deletedToCart(obj)
//        tableview.reloadData()
//        let str = GlobalDataHelper.instance.genInfoFromSelectCart()
//        moneyLabel.text = NSString(format: "¥%.01f",str.total) as String
//        if GlobalDataHelper.instance.goodsInCart.count == 0{
//            selectAllBtn.setBackgroundImage(UIImage(named: "uncheckmark"), forState: UIControlState.Normal)
//            selectAll = false
//            view.addSubview(noteInfo)
//        }
    }
    func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath){
        if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CartCell{
            cell.showEdit(true)
        }
    }
    func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath){
        if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CartCell{
            cell.showEdit(false)
        }
    }
}